<template>
	<!-- 子表单拖拽元素的实现 -->
<div
  v-if="element && element.key && element.type != 'block' && element.type!='editor'"
  class="widget-table-view widget-view-drag drag-widget" 
  :class="{active: selectWidget.key == element.key, 'is_req': element.options.required}"
  @click.stop="handleSelectWidget(index)"
  :style="{width: !element.options.width || element.options.width == '100%' ? '200px' : element.options.width}"
>
  <el-table
    row-class-name="widget-table-row"
    :data="[{}]">
    <el-table-column :label="element.name">
      <widget-element-item :element="element" :is-table="true"></widget-element-item>
    </el-table-column>
  </el-table>

  <div class="widget-view-action" v-if="selectWidget.key == element.key">
	<!-- 复制, 删除图标 -->
	<button type="button" class="show-circle action-clone">
		<i class="iconfont icon-icon_clone" @click.stop="handleWidgetClone(index)"></i>
	</button>
	<button type="button"  class="show-circle action-delete">
		<i class="iconfont icon-trash" @click.stop="handleWidgetDelete(index)"></i>
	 </button>
  </div>
<!-- <div class="widget-view-drag" v-if="selectWidget.key == element.key">
    <i class="iconfont icon-drag drag-widget"></i>
  </div> -->
</div>
</template>

<script>
import WidgetElementItem from './WidgetElementItem'
export default {
  components: {
    WidgetElementItem
  },
  props: ['element', 'select', 'index', 'data'],
  data () {
    return {
      selectWidget: this.select
    }
  },
  methods: {
    handleSelectWidget (index) {
      this.selectWidget = this.data[index]
    },
    handleWidgetDelete (index) {
      if (this.data.length == 1) {
        this.$emit('select-change', -1)
      } else {
        if (this.data.length - 1 == index) {
          this.$emit('select-change', index - 1)
        } else {
          this.$emit('select-change', index)
        }
      }

      this.$nextTick(() => {
        this.data.splice(index, 1)
      })
    },
    handleWidgetClone (index) {
      const key = new Date().getTime() + ''
      let cloneData = {
        ...this.data[index],
        options: {...this.data[index].options},
        key,
        model: this.data[index].type + key,
      }

      if (Object.keys(this.data[index].options).includes('options')) {
        cloneData = {
          ...cloneData,
          options: {
            ...cloneData.options,
            options: cloneData.options.options.map(item => ({...item}))
          }
        }
      }

      this.data.splice(index, 0, cloneData)

      this.$nextTick(() => {
        this.selectWidget = this.data[index + 1]
      })
    },
  },
  watch: {
    select (val) {
      this.selectWidget = val
    },
    selectWidget: {
      handler (val) {
        this.$emit('update:select', val)
      },
      deep: true
    }
  }
}
</script>
